<template>
  <div class="form-container">
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="80px" style="max-width: 980px" @submit.prevent>
      <div class="form-main">
        <div class="form-main-title">基础信息</div>
        <div class="form-main-content">
          <el-form-item label="所属分类" prop="categoryId">
            <cascader-classify v-model="formModel.categoryId" :category-type="1" style="width: 690px; margin-right: 20px" />
            <el-button type="primary" @click="openCategoryFormModal">添加分类</el-button>
          </el-form-item>
          <el-form-item label="考试名称" prop="examName">
            <el-input v-model="formModel.examName" maxlength="100" placeholder="请输入考试名称" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="选择试卷" prop="paperName">
            <el-input v-model="formModel.paperName" disabled class="item-form"></el-input>
            <el-button type="primary" @click="paperSelect">选择试卷</el-button>
          </el-form-item>
          <el-form-item label="考试说明" prop="description">
            <el-input v-model="formModel.description" type="textarea" maxlength="200" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="作答时限" prop="answerTime"> <el-input-number v-model="formModel.answerTime" :min="0" controls-position="right" />&nbsp;分钟 </el-form-item>
          <el-form-item label="合格标准" prop="passPercentage">
            <el-input-number v-model="formModel.passPercentage" :min="0" controls-position="right" />&nbsp;%
            <span class="tip" v-if="formModel.totalScore > 0">当前总分={{ formModel.totalScore }}分，合格分={{ (formModel.totalScore * formModel.passPercentage) / 100 }}分 </span>
          </el-form-item>
          <el-form-item label="销售价" prop="price">
            <el-input-number v-model="formModel.price" :min="0" :precision="2" controls-position="right" />&nbsp;元
            <span class="tip">0元，表示免费 </span>
          </el-form-item>
          <el-form-item label="划线价" prop="linePrice">
            <el-input-number v-model="formModel.linePrice" :min="0" :precision="2" controls-position="right" />&nbsp;元
            <span class="tip">划线价不能低于销售价 </span>
          </el-form-item>
          <!--
          <el-form-item label="虚拟学习人数" prop="countVirtualStudy">
            <el-input-number v-model="formModel.countVirtualStudy" :min="0" controls-position="right" />
            <span class="tip">页面显示的学习人数 = 真实的学习人数 + 虚拟学习人数</span>
          </el-form-item>
          <el-form-item label="虚拟购买人数" prop="countVirtualBuy">
            <el-input-number v-model="formModel.countVirtualBuy" :min="0" controls-position="right" />
            <span class="tip">页面显示的购买人数 = 真实的购买人数 + 虚拟购买人数</span>
          </el-form-item>
          -->
          <el-form-item label="考试类型" prop="examType">
            <enum-radio v-model="formModel.examType" :custom-list="examTypeList" />
            <!--            <span class="tip">正式考试，模拟考试</span>-->
          </el-form-item>
          <template v-if="formModel.examType === 1">
            <el-form-item class="form-group" label="有效期" prop="validityDateType">
              <el-radio-group v-model="formModel.validityDateType" style="flex-direction: column; align-items: flex-start">
                <div>
                  <el-radio :value="1">长期有效</el-radio>
                </div>
                <div>
                  <el-radio :value="2">有效天数</el-radio>
                  <el-input-number v-model="formModel.days" :disabled="formModel.validityDateType !== 2" :min="0" :precision="2" controls-position="right" />
                </div>
                <div>
                  <el-radio :value="3">固定周期</el-radio>
                  <el-date-picker
                    v-model="formModel.timeRange1"
                    :disabled="formModel.validityDateType !== 3"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    range-separator="到"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="handleTime1"
                  />
                </div>
              </el-radio-group>
            </el-form-item>
            <el-form-item class="form-group" label="次数限制" prop="examCount">
              <el-input-number v-model="formModel.examCount" :min="0" controls-position="right" /> &nbsp;次
              <span class="tip">模拟模式允许重复多次考试，0次，表示不限制 </span>
            </el-form-item>
            <el-form-item label="成绩设置" prop="examScoreType">
              <enum-radio v-model="formModel.examScoreType" :enum-name="'ExamScoreType'" />
              <span class="tip">若考试可多次情况下，用户的最终成绩 </span>
            </el-form-item>
          </template>
          <template v-if="formModel.examType === 2">
            <el-form-item class="form-group" label="报名时间" prop="validityDateType">
              <div>
                <el-date-picker
                  v-model="formModel.timeRange2"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  range-separator="到"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleTime2"
                />
              </div>
            </el-form-item>
            <el-form-item class="form-group" label="开考时间" prop="examStartTime">
              <div>
                <el-date-picker v-model="formModel.examStartTime" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" />
              </div>
            </el-form-item>
            <el-form-item class="form-group" label="报名限制" prop="registrationUserLimitCount">
              <el-input-number v-model="formModel.registrationUserLimitCount" :min="0" controls-position="right" />
              <span class="tip">报名模式可设置报名人数限制，0次，表示不限制 </span>
            </el-form-item>
            <el-form-item class="form-group" label="迟到限制" prop="allowableLate">
              <el-switch v-model="formModel.allowableLate" />
              <span class="tip">开启后，允许学员在考试开始进入考试 </span>
            </el-form-item>
            <el-form-item v-if="formModel.allowableLate" class="form-group" prop="speedDouble">
              <span>在考试开始后，<el-input-number v-model="formModel.allowableLateTime" :min="0" class="min-number" controls-position="right" /> 分钟内可以进入考试</span>
            </el-form-item>
          </template>
        </div>
      </div>
      <div class="form-main">
        <div class="form-main-title">考试设置</div>
        <div class="form-main-content">
          <!-- 功能待实现
          <el-form-item label="人脸识别" prop="faceId">
            <el-switch v-model="formModel.faceId" />
            <span class="tip">开启后，开始考试前需要人脸识别通过后才能进入考试 </span>
          </el-form-item>
          <div v-if="formModel.examType === 2">
            <el-form-item v-if="formModel.faceId" prop="faceId">
              <span>考试开始前 <el-input-number v-model="formModel.faceIdLimitTime" :min="0" class="min-number" controls-position="right" /> 分钟开始身份认证，</span>
              <span>每个学员允许最多认证 <el-input-number v-model="formModel.faceIdLimitCount" :min="0" class="min-number" controls-position="right" /> 次</span>
            </el-form-item>
            <el-form-item v-if="formModel.faceId" prop="faceId">
              <span>当认证失败后， <enum-select v-model="formModel.faceIdFailureEnter" :custom-list="system.selectAllow" :custom-width="'80px'" /> 进入考试</span>
              <span v-if="!formModel.faceIdFailureEnter">
                <span>， 同时 <enum-select v-model="formModel.faceIdFailureAppeal" :custom-list="system.selectSwitch" :custom-width="'80px'" /> 申请人工审核功能</span>
              </span>
            </el-form-item>
          </div>
          <el-form-item label="人脸抓拍" prop="faceCapture">
            <el-switch v-model="formModel.faceCapture" />
            <span class="tip">开启后，考试过程中会进行人脸抓拍 </span>
          </el-form-item>
          <el-form-item v-if="formModel.faceCapture" prop="faceCaptureTime">
            <div>考试过程中，每 <el-input-number v-model="formModel.faceCaptureTime" :min="0" class="min-number" controls-position="right" /> 分钟抓拍一次学员答题照片</div>
          </el-form-item>
          <el-form-item v-if="formModel.faceId && formModel.faceCapture" label="考试监测" prop="faceCaptureDetection">
            <el-switch v-model="formModel.faceCaptureDetection" />
            <span class="tip">开启后，会实时对学员进行人脸监测</span>
          </el-form-item>
          <el-form-item v-if="formModel.faceCaptureDetection" prop="faceCaptureTime">
            <span>考试中 <enum-select v-model="formModel.faceCaptureHighDetection" :custom-list="system.selectSwitch" :custom-width="'80px'" /> 高灵敏度监测，</span>
            <span>异常 <el-input-number v-model="formModel.faceCaptureFailureCount" :min="0" class="min-number" controls-position="right" /> 次后系统自动强制交卷</span>
          </el-form-item>
          -->
          <el-form-item label="切屏限制" prop="switchScreenLimit">
            <el-switch v-model="formModel.switchScreenLimit" />
          </el-form-item>
          <el-form-item v-if="formModel.switchScreenLimit">
            <span>切换到其他页面 <el-input-number v-model="formModel.switchScreenTime" :min="0" :max="30" class="min-number" controls-position="right" /> 秒后判定为切屏， </span>
            <span>超过 <el-input-number v-model="formModel.switchScreenCount" :min="0" :max="20" class="min-number" controls-position="right" /> 次后会强制交卷</span>
          </el-form-item>
          <el-form-item label="评阅方式" prop="evaluationMethod">
            <enum-radio v-model="formModel.evaluationMethod" :enum-name="'EvaluationMethod'" />
            <span class="tip">自动评阅：主观题默认不批改</span>
          </el-form-item>
          <el-form-item label="AI评阅" prop="aiGrading">
            <el-switch v-model="formModel.aiGrading" />
            <span class="tip">开启后，系统的主观题会自动用AI进行评阅</span>
          </el-form-item>
          <el-form-item label="成绩显示" prop="resultShow">
            <el-switch v-model="formModel.resultShow" />
            <span class="tip">开启后，交卷后可查看学员自己的成绩（主观题成绩不计入得分，需要人工评阅）</span>
          </el-form-item>
          <el-form-item v-if="formModel.resultShow" prop="resultShowRule">
            <enum-radio v-model="formModel.resultShowRule" :enum-name="'ResultShowRule'" />
            <span v-if="formModel.resultShowRule === 4">
              &nbsp;<el-date-picker v-model="formModel.resultShowTime" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" />
            </span>
          </el-form-item>
          <el-form-item label="答案显示" prop="answerShow">
            <el-switch v-model="formModel.answerShow" />
            <span class="tip">开启后，交卷后可查看试卷的答案解析</span>
          </el-form-item>
          <el-form-item v-if="formModel.answerShow" prop="answerShowRule">
            <enum-radio v-model="formModel.answerShowRule" :enum-name="'AnswerShowRule'" />
          </el-form-item>
          <el-form-item v-if="formModel.examType === 2" label="名次显示" prop="resultShowRank">
            <el-switch v-model="formModel.resultShowRank" />
            <span class="tip">开启后，学员能查看名次</span>
          </el-form-item>
          <el-form-item v-if="formModel.examType === 2 && formModel.resultShowRank" label="排行榜显示" prop="rankList">
            <el-switch v-model="formModel.rankList" />
            <span class="tip">开启后，学员能查看排行榜</span>
          </el-form-item>
          <el-form-item label="发布状态" prop="publishStatus">
            <enum-radio v-model="formModel.publishStatus" :enum-name="'publishStatus'" />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="form-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="onSubmit()">确定</el-button>
    </div>
  </div>
  <select-paper v-if="paper.visible" :visible="paper.visible" @close="handlePaper" />
  <category-form ref="categoryRef" />
</template>
<script setup>
  import { ElMessage } from 'element-plus'
  import { onMounted, reactive, ref } from 'vue'
  import { examApi } from '@/api/exam'
  import SelectPaper from '@/components/Selector/Paper/index.vue'
  import CascaderClassify from '@/components/Cascader/Classify/index.vue'
  import EnumRadio from '@/components/Enum/Radio/index.vue'
  import EnumSelect from '@/components/Enum/Select/index.vue'
  import { useRouter } from 'vue-router'
  import { useRoute } from 'vue-router/dist/vue-router'
  import * as system from '@/utils/constants.js'
  import { examTypeList } from '@/utils/constants.js'
  import CategoryForm from '@/views/common/category/CategoryForm.vue'

  const router = useRouter()

  // 分类添加
  const categoryRef = ref()
  const openCategoryFormModal = (item = null, parentId = '') => {
    categoryRef.value.onOpen(item, parentId)
  }

  //  模拟考试-固定周期时间
  const handleTime1 = (date) => {
    if (date) {
      formModel.beginTime = date[0] + ' 00:00'
      formModel.endTime = date[1] + ' 23:59'
    } else {
      formModel.beginTime = ''
      formModel.endTime = ''
    }
  }

  //  正式考试-报名时间
  const handleTime2 = (date) => {
    if (date) {
      formModel.registrationStartTime = date[0] + ' 00:00'
      formModel.registrationEndTime = date[1] + ' 23:59'
    } else {
      formModel.registrationStartTime = ''
      formModel.registrationEndTime = ''
    }
  }

  // 试卷选择功能
  const paper = reactive({
    visible: false
  })
  const paperSelect = () => {
    paper.visible = true
  }
  const handlePaper = (item) => {
    paper.visible = false
    if (item) {
      formModel.paperName = item.paperName
      formModel.paperId = item.id
      formModel.answerTime = item.answerTime
      formModel.passPercentage = item.passPercentage
      formModel.totalScore = item.totalScore
    }
  }

  // 校验规则
  const formRef = ref()
  const rules = {
    categoryId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    examName: [{ required: true, message: '不能为空', trigger: 'blur' }],
    paperName: [{ required: true, message: '不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '不能为空', trigger: 'blur' }],
    answerTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
    passPercentage: [{ required: true, message: '不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '不能为空', trigger: 'blur' }],
    linePrice: [{ required: true, message: '不能为空', trigger: 'blur' }],
    countVirtualStudy: [{ required: true, message: '不能为空', trigger: 'blur' }],
    countVirtualBuy: [{ required: true, message: '不能为空', trigger: 'blur' }],
    validityDateType: [{ required: true, message: '不能为空', trigger: 'blur' }],
    examCount: [{ required: true, message: '不能为空', trigger: 'blur' }],
    examStartTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
    registrationUserLimitCount: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }

  // 表单
  const loading = ref(false) // 加载进度状态
  const emit = defineEmits(['refresh'])
  const formDefault = {
    id: undefined,
    examType: 1, // 考试类型(1模拟考试， 2正式考试)
    categoryId: undefined,
    examName: undefined,
    answerTime: 90,
    passPercentage: 60,
    price: 0,
    linePrice: 0,
    countVirtualBuy: 0, // 虚拟购买人数
    countVirtualStudy: 0, // 虚拟学习人数
    validityDateType: 1, // examType=1，有效期类型(1：长期有效、2：有效天数、3：固定周期)
    examCount: 0, // examType=1，考试次数
    examScoreType: 1, // examType=1,考试成绩设置(1：记录学员最高成绩、2：记录学员最新成绩)
    switchScreenLimit: false, // 切屏限制
    switchScreenTime: 5,
    switchScreenCount: 3,
    evaluationMethod: 1, // 评阅方式(1:系统评阅，2:人工评阅)
    aiGrading: false, // AI阅卷
    resultShow: true, // 成绩显示
    resultShowRule: 1, // 成绩显示规则(1：交卷后、2：考试结束后、3：隐藏、4：自定义时间)
    resultShowTime: undefined, // resultShowRule=4,显示时间
    answerShow: true, // 答案显示
    answerShowRule: 1, // 答案显示规则(1：查看对错和答案解析、2：只看对错)
    faceId: false, // 人脸识别功能
    faceCapture: false, // 人脸抓拍功能
    faceCaptureTime: 5, // 人脸抓拍时长间隔(单位：分钟，取值范围：1~30)
    faceCaptureDetection: false, // 人脸抓拍检测功能
    faceCaptureHighDetection: false, // 人脸抓拍检测功能：高灵敏度功能
    faceCaptureFailureCount: 1, // 人脸抓拍检测功能：限制错误次数(1~99)
    registrationStartTime: '', // examType=2,报名开始时间
    registrationEndTime: '', // examType=2,报名结束时间
    registrationUserLimitCount: 0, // examType=2,报名人数限制
    examStartTime: '', // examType=2,考试开始时间
    allowableLate: false, // examType=2,允许迟到功能
    allowableLateTime: 5, // examType=2,迟到时间，单位：分钟
    faceIdLimitTime: 15, // examType=2,考试开考前人脸识别限制时间(单位：分钟，内容范围：1~30)
    faceIdLimitCount: 3, // examType=2,考试开考前人脸识别允许错误次数(单位：次，内容范围：1~99)
    faceIdFailureEnter: false, // examType=2,考试开考前人脸识别失败允许考试
    faceIdFailureAppeal: false, // examType=2,考试开考前人脸识别失败允许申诉
    noticeBefore: false, // examType=2,开考前是否通知
    noticePublishedScore: false, // examType=2,成绩出来是否通知
    resultShowRank: true, // examType=2,名次显示
    rankList: true, // examType=2,排行榜显示
    publishStatus: 0 // 发布状态(0：未发布，1：已发布)
  }
  const formModel = reactive({ ...formDefault })
  // 提交
  const onSubmit = async () => {
    // 校验
    const valid = await formRef.value.validate()
    if (!valid) return

    if (loading.value === true) {
      ElMessage.warning('正在处理···')
      return
    }
    delete formModel.timeRange2
    delete formModel.timeRange1

    loading.value = true
    try {
      if (formModel.id) {
        // 修改
        if (formModel.examType === 1) {
          await examApi.examMockEdit(formModel)
        }
        if (formModel.examType === 2) {
          await examApi.examRegistrationEdit(formModel)
        }
        ElMessage.success('修改成功')
      } else {
        // 添加
        if (formModel.examType === 1) {
          await examApi.examMockSave(formModel)
        }
        if (formModel.examType === 2) {
          await examApi.examRegistrationSave(formModel)
        }
        ElMessage.success('添加成功')
      }
      handleClose()
      emit('refresh')
    } finally {
      loading.value = false
    }
  }
  // 初始化
  const route = useRoute()
  onMounted(async () => {
    if (route.query.examId) {
      let res = await examApi.examView({ id: route.query.examId })
      Object.assign(formModel, res)
      // 考试类型（1模拟考试，2正式考试）
      if (formModel.examType === 1) {
        formModel.timeRange1 = [formModel.beginTime, formModel.endTime]
      }
      if (formModel.examType === 2) {
        formModel.timeRange2 = [formModel.registrationStartTime, formModel.registrationEndTime]
      }
    } else {
      Object.assign(formModel, formDefault)
    }
    if (route.query.isCopy) {
      formModel.id = undefined
    }
  })
  const handleClose = () => {
    router.go(-1)
  }
</script>
<style lang="scss" scoped>
  .item-form {
    width: 690px;
    margin-right: 20px;
  }
</style>
